package com.handpay.zztong.hp.other.activity;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Bundle;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.DownloadListener;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.handpay.framework.ClientEngine;
import com.handpay.framework.LuaTableUtil;
import com.handpay.framework.MD5;
import com.handpay.framework.swiper.IBusinessSwiper;
import com.handpay.framework.swiper.SwiperMode;
import com.handpay.framework.utils.CommonUtils;
import com.handpay.zztong.hp.R;
import com.handpay.zztong.hp.base.activity.ZZTongActivity;
import com.handpay.zztong.hp.swiper.activity.VPOSActivity;

import com.handpay.zztong.hp.bean.ActionBar;
import com.handpay.zztong.hp.log.HPLog;
import com.handpay.zztong.hp.permission.PermissionRequestCode;
import com.handpay.zztong.hp.ui.ZZTShowDialog;
import com.handpay.zztong.hp.utils.AccountUtils;
import com.handpay.zztong.hp.utils.WuXianDesUtil;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

import se.krka.kahlua.vm.LuaTable;
import se.krka.kahlua.vm.LuaTableImpl;

/**
 * 显示HTML内容
 *
 * @author ppliu
 */
public class ShowHtmlActivity extends ZZTongActivity implements OnClickListener {

    /**
     * 页面标题
     */
    public static final String ShowHtml_Title_Key = "ShowHtml_Title_Key";

    /**
     * 要显示的html路径
     */
    public static final String ShowHtml_Html_Path_Key = "ShowHtml_Html_Path_Key";
    /**
     * 加载网页的webview
     */
    public WebView webView;
    /**
     * 网页加载的地址
     */
    private String mallUrl;

    @Override
    protected boolean isShownTabs() {
        return false;
    }

    @Override
    protected boolean isShownTopBar() {
        return true;
    }

    @Override
    public ActionBar getActivityActionBar() {
        //leftBar goBack();
        return new ActionBar(this.getString(R.string.register_title), true);
    }

    public static Map<String, String> map = new HashMap<String, String>();

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        this.setContentView(R.layout.activity_show_html);
        super.onCreate(savedInstanceState);

        if (getIntent().getStringExtra(ShowHtml_Title_Key).equals(getString(R.string.phone_charge)) || getIntent().getStringExtra(ShowHtml_Title_Key).equals(getString(R.string.qb_charge)) || getIntent().getStringExtra(ShowHtml_Title_Key).equals(getString(R.string.game_charge))) {
            myActionBar.setVisibility(View.GONE);
            (findViewById(R.id.btn_goToFunction)).setOnClickListener(this);
        } else {
            myActionBar.setTitleText(getIntent().getStringExtra(ShowHtml_Title_Key));
            (findViewById(R.id.btn_goToFunction)).setVisibility(View.GONE);
        }
        webView = ((WebView) findViewById(R.id.userServiceWebView));
        // 开启 DOM storage API 功能 
        webView.getSettings().setDomStorageEnabled(true);
        webView.getSettings().setLoadsImagesAutomatically(true); // 支持自动加载图片
        final ProgressBar progressBar = (ProgressBar) this.findViewById(R.id.progressBar);

        View view = findViewById(android.R.id.list);

        if (getString(R.string.Help_center).equals(getIntent().getStringExtra(ShowHtml_Title_Key)) && null != view) {
            view.setVisibility(View.VISIBLE);
            progressBar.setVisibility(View.GONE);
        } else {
            // 允许使用JS
            webView.getSettings().setJavaScriptEnabled(true);
            // 禁用web view 的滚动条，否则右侧会有白边
            webView.setHorizontalScrollBarEnabled(true);
            webView.setVerticalScrollBarEnabled(false);
            webView.setDownloadListener(new DownloadListener() {
                @Override
                public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
                    HPLog.i("tag", "url=" + url);
                    HPLog.i("tag", "userAgent=" + userAgent);
                    HPLog.i("tag", "contentDisposition=" + contentDisposition);
                    HPLog.i("tag", "mimetype=" + mimetype);
                    HPLog.i("tag", "contentLength=" + contentLength);
                    Uri uri = Uri.parse(url);
                    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                    startActivity(intent);
                    goBack();
                }
            });
            webView.requestFocus();
            mallUrl = getIntent().getStringExtra(ShowHtml_Html_Path_Key);
            HPLog.i("ShowHtmlActivity", "mallUrl:" + mallUrl);
            webView.loadUrl(mallUrl);
//    	    if(!getString(R.string.Help_center).equals(getIntent()
//                    .getStringExtra(ShowHtml_Title_Key))){
            webView.setWebViewClient(new WebViewClient() {

                @Override
                public void onPageStarted(WebView view, String url, Bitmap favicon) {
                    super.onPageStarted(view, url, favicon);
//						HPLog.e("ShowHtmlActivity onPageStarted", url);

                }

                @Override
                public void onPageFinished(WebView view, String url) {
                    super.onPageFinished(view, url);
                    String username = AccountUtils.getAccountName(ShowHtmlActivity.this);
                    String channel = ClientEngine.CHANNEL;
                    webView.loadUrl("javascript:if (typeof setAccountAndChannel != 'undefined' && setAccountAndChannel instanceof Function) {	setAccountAndChannel('" + username + "','" + channel + "');}");
                }

                @Override
                public boolean shouldOverrideUrlLoading(WebView view, String url) {
                    // 重写此方法表明点击网页里面的链接还是在当前的webview里跳转，不跳到浏览器那边`
                    HPLog.e("ShowHtmlActivity shouldOverrideUrlLoading", url);
                    if (url.equals("vpos://exit")) {

                    } else if (url.startsWith("http://handpay/orderPayment")) {
                        //supplierCode=xxx&orderID=xxx&orderTime=xxx&signData=xxx";
                        Map<String, String> map = CommonUtils.getUrlParamsMap(url);
                        String supplierCode = map.get("supplierCode");
                        String orderID = map.get("orderID");
                        String orderTime = map.get("orderTime");
                        String signData = map.get("signData");
                        String key = supplierCode + "|" + orderID + "|" + orderTime + "|" + AccountUtils.getAccountName(ShowHtmlActivity.this);
                        String token = MD5.toMD5(key);
                        HPLog.i(HPLog.YL_TAG, "key:" + key);
                        HPLog.i(HPLog.YL_TAG, "signData:" + signData);
                        HPLog.i(HPLog.YL_TAG, "token:" + token);
                        if (signData.equals(token)) {
                            final ZZTShowDialog mDialog = new ZZTShowDialog(ShowHtmlActivity.this, R.layout.dialog_market, R.style.DialogSlideAnim);
                            Window window = mDialog.getDialog().getWindow();
                            window.setGravity(Gravity.BOTTOM);
                            window.setBackgroundDrawableResource(android.R.color.transparent);
                            WindowManager.LayoutParams lp = window.getAttributes();
                            lp.width = screenWidth;
                            window.setAttributes(lp);
                            mDialog.setDialogCallback(new ZZTShowDialog.Dialogcallback() {
                                @Override
                                public void ButtonOk() {

                                }

                                @Override
                                public void ButtonCancle() {
                                    mDialog.dismiss();
                                }
                            });
                            mDialog.show();
                        }
                    } else if (url.equals("vpos://getUserName")) {

                    } else if (url.equals("handpaycolorful://getUserName")) {

                    } else if (url.startsWith("vpos://getUserLocation")) {

                    } else if (url.startsWith("vpos://mallPayment")) {
                        try {

                        } catch (Exception e) {
                        }
                    } else if (url.startsWith("tel://")) {
                        try {
                            String[] newstr = url.split("//");
                            Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + newstr[1]));
                            startActivity(intent);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else if (url.startsWith("vpos://payment")) {
                        try {
                            url = url.replace("vpos://payment?", "");
                            LuaTableImpl table = parsePaymentInfo(url);
                            HPLog.e(HPLog.YL_TAG, "打印商城订单信息");
                            LuaTableUtil.printTable(table);
                            map = LuaTableToMap(table);
                            SwiperMode m = SwiperMode.SUPER_TRANS;//这里必须写为super_trans,因为涉及到加密数据的处理方式
                            setMode(m, false, new Runnable() {
                                @Override
                                public void run() {
                                    final Hashtable<String, Object> params = new Hashtable<String, Object>();
                                    params.put(ZZTongActivity.ACTION, Action_Phone);//这里本应该是根据点击的不同应用,而传递对应的action,但是没有大的区别就没判断。如果后面要接入99商城那就要细分了。
                                    //只有在下单成功的情况下,才视为交易,在这里加一个消费通知的标记,方便后面判断使用
                                    ClientEngine.getInstance().saveGlobal(IBusinessSwiper.BANK_TransactionType_KEY, "PurchaseAdvice");
                                    Intent intent = getIntent(ShowHtmlActivity.this, VPOSActivity.class, params);
                                    intent.putExtra(ForResult, false);
                                    startActivity(intent);
                                }
                            });
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else {
                        HPLog.e("fyang", "直接加载url");
                        view.loadUrl(url);
                    }
                    return true;
                }

                @Override
                public void onReceivedSslError(WebView view, final SslErrorHandler handler, SslError error) {
//        				handler.proceed();//ssl验证错误继续加载页面可能导致被中间人攻击
                    //更具ssl code 让用户选择是否加载
                    int errorCode = error.getPrimaryError();
                    showAlertDialog(ShowHtmlActivity.this, ShowHtmlActivity.this.getString(R.string.tip), "SSL错误[" + errorCode + "]，是否继续加载？", false, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            handler.proceed();
                        }
                    }, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            handler.cancel();
                        }
                    });
                }
            });
//    	    }
            webView.setWebChromeClient(new WebChromeClient() {
                @Override
                public void onProgressChanged(WebView view, int newProgress) {
//                    HPLog.i("ShowHtmlActivity", "newProgress:" + newProgress);
                    if (newProgress >= 100) {
                        progressBar.setVisibility(View.GONE);
                    }
                }
            });
        }
    }

    @Override
    public void onSucceed(int requestCode, List<String> grantPermissions) {
        if (requestCode == PermissionRequestCode.REQUEST_CODE_PERMISSION_CALL_PHONE) {
            Toast.makeText(this, R.string.message_phone_succesed, Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onSwiperPlugOff() {
        String title = getIntent().getStringExtra(ShowHtml_Title_Key);
        String superTitle = getString(R.string.super_transfer_agreement);
        //超级转账
        if (superTitle.equals(title)) {
            onFunctionTab(null);
        }
    }

    /**
     * 返回事件的处理
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        String title = getIntent().getStringExtra(ShowHtml_Title_Key);
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (title.equals(getString(R.string.phone_charge)) || title.equals(R.string.qb_charge) || title.equals(R.string.game_charge)) {
                onFunctionTab(null);
            } else {
                this.finish();
            }
        }
        return false;
    }

    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.btn_goToFunction) {
//            onFunctionTab(null);
            finish();
        }
    }

    /**
     * 解析下单数据
     *
     * @param url
     * @return
     */
    private LuaTableImpl parsePaymentInfo(String url) {
        LuaTableImpl luaVector = new LuaTableImpl();
        try {
            url = URLDecoder.decode(url, "utf-8");
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
            dealGetOrderIdFail();
        }
        String[] strs = url.split("&");

        for (String string : strs) {
            String[] splitMsg = string.split("=");
            if (splitMsg.length > 1) {
                String rdata = null;
                try {
                    //解密商城订单数据
                    rdata = WuXianDesUtil.decrypt(splitMsg[1], "handpay2014!@#$%");
                } catch (Exception e) {
                    e.printStackTrace();
                    dealGetOrderIdFail();
                }
                luaVector.rawset(splitMsg[0], new String(rdata));
            }
        }
        return luaVector;
    }

    public Map<String, String> LuaTableToMap(LuaTable table) {
        try {
            map.put("transAmount", (String) table.rawget("transAmount"));
            map.put("merchantName", (String) table.rawget("cMerName"));
            map.put("terminalId", (String) table.rawget("terminalId"));
            map.put("orderId", (String) table.rawget("pOrderId"));
            map.put("type", (String) table.rawget("type"));
            map.put("pSubTime", (String) table.rawget("pSubTime"));
            map.put("merchantId", (String) table.rawget("cMerId"));
            map.put("merchantCountry", (String) table.rawget("cMerCountry"));
            HPLog.d(HPLog.YL_TAG, "map---" + map.toString());
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            dealGetOrderIdFail();
        }
        return map;
    }

    /**
     * 处理下单失败
     * 原则上不论任何原因导致下单失败,交易都应该终止
     */
    public void dealGetOrderIdFail() {
        HPLog.d(HPLog.YL_TAG, "map---dealGetOrderIdFail");
        if (map != null) {
            map.clear();
        }
        showAlertDialog(ShowHtmlActivity.this, getResources().getString(R.string.tip_title), getResources().getString(R.string.get_orderid_fail), false, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                ShowHtmlActivity.this.finish();
            }
        });
    }


    @Override
    public void goToVPos() {
        super.goToVPos();
        SwiperMode m = SwiperMode.SUPER_TRANS;//这里必须写为super_trans,因为涉及到加密数据的处理方式
        setMode(m, false, new Runnable() {
            @Override
            public void run() {
                /*final Hashtable<String,Object> params = new Hashtable<String,Object>();
                params.put(ZZTongActivity.ACTION, Action_Phone);//这里本应该是根据点击的不同应用,而传递对应的action,但是没有大的区别就没判断。如果后面要接入99商城那就要细分了。
				//只有在下单成功的情况下,才视为交易,在这里加一个消费通知的标记,方便后面判断使用
				ClientEngine.getInstance().saveGlobal(IBusinessSwiper.BANK_TransactionType_KEY, "PurchaseAdvice");
				Intent intent = getIntent(ShowHtmlActivity.this, VPOSActivity.class, params);
				intent.putExtra(ForResult, false);
				startActivity(intent);*/
                webView.loadUrl(mallUrl);
            }
        });
    }

    @Override
    protected void onDestroy() {
        HPLog.i(HPLog.TAG_RESULT,"--onDestroy--");
        destoryWebView();
        super.onDestroy();
    }

    private void destoryWebView(){
        if(webView!=null) {
            // 先从父控件中移除WebView
            ViewParent parent = webView.getParent();
            if (parent != null) {
                ((ViewGroup) parent).removeView(webView);
            }
            webView.stopLoading();
            webView.getSettings().setJavaScriptEnabled(false);
            webView.clearHistory();
            webView.removeAllViews();
            webView.destroy();
        }
    }
}
